package com.exsun.ex1077.ui.popup

import android.content.Context
import android.view.View
import android.widget.TextView
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.view.TimePickerView
import com.exsun.ex1077.R
import com.lxj.xpopup.core.BottomPopupView
import com.zhangping.fastjetpack.binding.gone
import com.zhangping.fastjetpack.binding.visible
import com.zhangping.fastjetpack.callback.TwoCallback
import com.zhangping.fastjetpack.extend.*
import com.zhangping.fastjetpack.extend.view.textString
import kotlinx.android.synthetic.main.layout_time_select_view.view.*
import kotlinx.android.synthetic.main.popup_msg.view.*
import kotlinx.android.synthetic.main.popup_time_select.view.*
import java.util.*

/**
 * 描述：时间选择弹窗
 * 作者：ZhangPing
 * 创建时间：2023/3/20 17:21
 */
class TimeSelectPopup(context: Context,val onSelectListener: TwoCallback<Date, Date>): BottomPopupView(context) {

    override fun getImplLayoutId() = R.layout.popup_time_select

    companion object{
        const val TAB_MODE_MONTH = 0
        const val TAB_MODE_CUSTOM = 1
        const val CUSTOM_TIME_MODE_START = 0
        const val CUSTOM_TIME_MODE_END = 1
    }

    private lateinit var timePicker: TimePickerView
    private var tabMode = TAB_MODE_MONTH
    private var customTimeMode = -1
    private lateinit var lastTimeViewList: List<View>

    override fun onCreate() {
        initTimePicker()
        close.setOnClickListener { dismiss() }
        monthMode.setOnClickListener {
            if (tabMode == TAB_MODE_MONTH) return@setOnClickListener
            setMode(TAB_MODE_MONTH)
        }
        customMode.setOnClickListener {
            if (tabMode == TAB_MODE_CUSTOM) return@setOnClickListener
            setMode(TAB_MODE_CUSTOM)
        }
        confirm.setOnClickListener { timePicker.returnData() }
    }

    /**
     * 初始化时间滚轮
     */
    private fun initTimePicker(){
        timePicker = TimePickerBuilder(activity) { date, v ->
            if (tabMode == TAB_MODE_MONTH){
                val calendar = Calendar.getInstance()
                calendar.time = date
                calendar.set(Calendar.DAY_OF_MONTH, 1)
                val startDate = calendar.time
                if (date.month == Date().month) {
                    //是当月则结束时间只需要到今日
                    onSelectListener.onCall(startDate, Date())
                }else{
                    calendar.add(Calendar.MONTH, 1)
                    calendar.add(Calendar.DAY_OF_MONTH, -1)
                    val endDate = calendar.time
                    onSelectListener.onCall(startDate, endDate)
                }
            }else if (tabMode == TAB_MODE_CUSTOM){
                val startTimeDate = (timePicker.findViewById(R.id.startTime) as TextView).textString().toDate(format = "yyyy-MM-dd")
                val endTimeDate = (timePicker.findViewById(R.id.endTime) as TextView).textString().toDate(format = "yyyy-MM-dd")
                if (startTimeDate.after(endTimeDate)){
                    "结束时间不能小于开始时间".showToast()
                    return@TimePickerBuilder
                }
                onSelectListener.onCall(startTimeDate, endTimeDate)
            }
            dismiss()
        }
            .setLayoutRes(R.layout.layout_time_select_view){
                if (tabMode == TAB_MODE_MONTH){
                    it.headerView.gone()
                }else if (tabMode == TAB_MODE_CUSTOM){
                    it.headerView.visible()
                    lastTimeViewList = arrayListOf(it.lastOneMonth, it.lastThreeMonth, it.lastOneYear)
                    it.lastOneMonth.setOnClickListener { selectedLastTime(0) }
                    it.lastThreeMonth.setOnClickListener { selectedLastTime(1) }
                    it.lastOneYear.setOnClickListener { selectedLastTime(2) }
                    //初始化默认时间
                    it.startTime.text = getMonthFirstDate().toDateStr()
                    it.endTime.text = Date().toDateStr()
                    it.startTime.setOnClickListener{
                        customTimeMode = CUSTOM_TIME_MODE_START
                        startTime.setBackgroundResource(R.drawable.shape_radius3_bg_f2f2f5_bg_theme)
                        endTime.setBackgroundResource(R.drawable.shape_radius3_bg_f2f2f5)
                        timePicker.setDate(it.startTime.text.toString().toDate("yyyy-MM-dd").toCalendar())
                    }
                    it.endTime.setOnClickListener{
                        customTimeMode = CUSTOM_TIME_MODE_END
                        startTime.setBackgroundResource(R.drawable.shape_radius3_bg_f2f2f5)
                        endTime.setBackgroundResource(R.drawable.shape_radius3_bg_f2f2f5_bg_theme)
                        timePicker.setDate(it.endTime.text.toString().toDate("yyyy-MM-dd").toCalendar())
                    }
                }
            }
            .setDecorView(container)
            .setOutSideCancelable(false)
            .apply {
                when(tabMode){
                    TAB_MODE_MONTH -> {
                        setType(booleanArrayOf(false, true, false, false, false, false))
                    }
                    TAB_MODE_CUSTOM -> {
                        setType(booleanArrayOf(true, true, true, false, false, false))
                        setTimeSelectChangeListener {
                            if (customTimeMode == CUSTOM_TIME_MODE_START){
                                val startTimeView = timePicker.findViewById(R.id.startTime) as TextView
                                startTimeView.text = it.toDateStr()
                            }else if (customTimeMode == CUSTOM_TIME_MODE_END){
                                val endTimeView = timePicker.findViewById(R.id.endTime) as TextView
                                endTimeView.text = it.toDateStr()
                            }else {
                                //默认选中开始时间
                                customTimeMode = CUSTOM_TIME_MODE_START
                                startTime.setBackgroundResource(R.drawable.shape_radius3_bg_f2f2f5_bg_theme)
                                endTime.setBackgroundResource(R.drawable.shape_radius3_bg_f2f2f5)
                                val startTimeView = timePicker.findViewById(R.id.startTime) as TextView
                                startTimeView.text = it.toDateStr()
                            }
                        }
                    }
                }
            }
            .build().run {
                setKeyBackCancelable(false)
                show(false)
                this
            }
    }

    private fun selectedLastTime(position: Int){
        if (lastTimeViewList.isNullOrEmpty()) return
        lastTimeViewList.forEachIndexed { index, view ->
            view.setBackgroundResource(if (index == position) R.drawable.shape_radius3_bg_theme else R.drawable.shape_radius3_bd_theme)
            (view as TextView).setTextColor(if (index == position) R.color.white.toColorRes() else R.color.theme.toColorRes())
        }
        val calendar = Calendar.getInstance()
        when(position){
            0 -> {
                //上月
                calendar.add(Calendar.MONTH, -1)
                val date = calendar.time
                onSelectListener.onCall(getMonthFirstDate(date), getMonthLastDate(date))
            }
            1 -> {
                //近三月
                calendar.add(Calendar.MONTH, -2)
                onSelectListener.onCall(getMonthFirstDate(calendar.time), Date())
            }
            2 -> {
                //近一年
                calendar.add(Calendar.YEAR, -1)
                onSelectListener.onCall(getMonthFirstDate(calendar.time), Date())
            }
        }
        dismiss()
    }

    private fun setMode(tabMode: Int){
        this.tabMode = tabMode
        if (tabMode == TAB_MODE_MONTH){
            modeMonthText.setTextColor(R.color.theme.toColorRes())
            modeMonthBar.visible()
            modeCustomText.setTextColor(R.color.color_696969.toColorRes())
            modeCustomBar.gone()
        }else if (tabMode == TAB_MODE_CUSTOM){
            modeMonthText.setTextColor(R.color.color_696969.toColorRes())
            modeMonthBar.gone()
            modeCustomText.setTextColor(R.color.theme.toColorRes())
            modeCustomBar.visible()
        }
        if (isCreated){
            timePicker.dismiss()
            initTimePicker()
        }
    }

}